var myFeatureTable1;
var changeDetectionLayerUrl;

require([
    "dojo/ready",
    "dojo/parser",
    "dojo/_base/array",
    "dojo/parser", "dojo/on", "dojo/dom",

    "esri/symbols/SimpleMarkerSymbol",
    "esri/symbols/SimpleLineSymbol",
    "esri/symbols/SimpleFillSymbol",
    "esri/symbols/PictureMarkerSymbol",

    "esri/toolbars/draw",
    "esri/graphic",
    "esri/map",
    "esri/geometry/Extent",
    "esri/Color",

    "esri/layers/GraphicsLayer",
    "esri/layers/ArcGISDynamicMapServiceLayer",
    "esri/layers/ArcGISTiledMapServiceLayer",
    "esri/layers/FeatureLayer",
    "esri/InfoTemplate",
    "esri/dijit/FeatureTable",
    "esri/tasks/query",
    "dojo/domReady!"
], function (ready, parser, arrayUtils,
    parser, on, dom, SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, PictureMarkerSymbol,
    Draw, Graphic, Map, Extent, Color, GraphicsLayer, ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer, FeatureLayer, InfoTemplate,
    FeatureTable, Query) {
    parser.parse();

    initChangeDetection = function () {
        clickQueryGraphicsLayer1 = new GraphicsLayer({
            id: "clickQueryGraphicsLayer1",
        });

        clickQueryGraphicsLayer2 = new GraphicsLayer({
            id: "clickQueryGraphicsLayer2",
        });
    }

    var changeDetectionLayers0 = [];
    var changeDetectionLayers1 = [];


    on(dom.byId("changeDetectionBtn"), "click", function () {
        // var year = $("input[name='detectionOptionsRadios']:checked");

        $("#compareMapRow2").hide();
        // $(".compareMapRow").css("height", "100%");
        $("#compareMapRow3").css("display", "flex");
        $(".compareMapRow").css("height", "50%");

        $("#changeDetectionTab0").hide();
        $("#changeDetectionTab1").hide();

        maps[0].removeAllLayers();
        maps[1].removeAllLayers();

        var types = [];
        var ids = [];
        changeDetectionLayers0 = [];
        changeDetectionLayers1 = [];

        $("input[name='detectionType']:checked").each(function (i) {
            var type = $(this).val()
            types.push(type);
        });


        // var infoTemplate = new InfoTemplate("${name}");


        var year = $("input[name='detectionOptionsRadios']:checked").val();
        if (year == "1823") {
            var tiledMapServiceLayer0 = initTileLayer("1802");
            var tiledMapServiceLayer1 = initTileLayer("1803");
            $("#label_0").text("2018年二季度卫星影像");
            $("#label_1").text("2018年三季度卫星影像");
            types.map((item) => {
                if (item == "water") {
                    changeDetectionLayers0.push(initFeatureLayer(2));
                    changeDetectionLayers1.push(initFeatureLayer(2));
                    ids.push(2);
                } else if (item == "building") {
                    changeDetectionLayers0.push(initFeatureLayer(1));
                    changeDetectionLayers1.push(initFeatureLayer(1));

                    ids.push(1);
                }
            });

        } else if (year == "1834") {
            var tiledMapServiceLayer0 = initTileLayer("1803");
            var tiledMapServiceLayer1 = initTileLayer("1804");
            $("#label_0").text("2018年三季度卫星影像");
            $("#label_1").text("2018年四季度卫星影像");
            types.map((item) => {
                if (item == "water") {
                    ids.push(4);
                    changeDetectionLayers0.push(initFeatureLayer(4));
                    changeDetectionLayers1.push(initFeatureLayer(4));

                } else if (item == "building") {
                    changeDetectionLayers0.push(initFeatureLayer(3));
                    changeDetectionLayers1.push(initFeatureLayer(3));

                    ids.push(3);
                }
            });
        }

        ids.push(5);

        changeDetectionLayers0.push(initExtentLayer(5));
        changeDetectionLayers1.push(initExtentLayer(5));

        maps[0].addLayers([tiledMapServiceLayer0].concat(changeDetectionLayers0));
        maps[1].addLayers([tiledMapServiceLayer1].concat(changeDetectionLayers1));

        // var center = new esri.geometry.Point(-25220, 23200, map.spatialReference);
        // maps[0].centerAndZoom(center, 5);
        // maps[1].centerAndZoom(center, 5);

        types.forEach(item => {
            if (item == "water") {
                $("#changeDetectionTab1").show();
            } else if (item == "building") {
                $("#changeDetectionTab0").show();
            }
        })

        createFeatureTable1(changeDetectionLayers0[0]);


        $("#map_0").show();
        $("#map_1").show();

        $("#mainMap").hide();
        $("#compareMap").show();


    })

    $("#changeDetectionTab0").click(function () {
        createFeatureTable1(changeDetectionLayers0[0]);

    })

    $("#changeDetectionTab1").click(function () {
        createFeatureTable1(changeDetectionLayers0[1]);

    })



    function initTileLayer(satYear) {
        let url;
        satLayerUrls.forEach(item => {
            if (Object.keys(item)[0] == satYear) {
                url = item[satYear];
            }
        })

        return new ArcGISTiledMapServiceLayer(url + "?token=" + GLOBAL_TOKEN, {
            maxScale: 499,
            minScale: 500000
        });
    }


    function initFeatureLayer(i) {
        var region = $("input[name='detectionRegion']:checked").val();

        changeDetectionLayerUrls.forEach(currentItem => {
            if (Object.keys(currentItem)[0] == region) {
                changeDetectionLayerUrl = currentItem[Object.keys(currentItem)[0]];
            }
        })

        var fLayer = new FeatureLayer(changeDetectionLayerUrl + "/" + i, {
            // mode: FeatureLayer.MODE_ONDEMAND,
            mode: FeatureLayer.MODE_SNAPSHOT,//使用快照模式，防止缩放的时候绘制的图形是简化的
            outFields: ['st_area(shape)', 'st_length(shape)'],
            // outFields: ['st_area(shape)', 'st_length(shape)','area','length'],
            visible: true,
            // infoTemplate: infoTemplate,

        });

        // fLayer.on("load", function (e) {

        //     console.log(e.layer)

        // })

        return fLayer


    }

    function initExtentLayer(i) {

        var region = $("input[name='detectionRegion']:checked").val();

        changeDetectionLayerUrls.forEach(currentItem => {
            if (Object.keys(currentItem)[0] == region) {
                changeDetectionLayerUrl = currentItem[Object.keys(currentItem)[0]];
            }
        })

        var fLayer = new FeatureLayer(changeDetectionLayerUrl + "/" + i, {
            mode: FeatureLayer.MODE_ONDEMAND,
            outFields: ['st_area(shape)', 'st_length(shape)'],
            visible: true,
            // infoTemplate: infoTemplate,

        });

        fLayer.on("load", function (e) {

            console.log(e.layer)
            maps[0].setExtent(fLayer.initialExtent);
            maps[1].setExtent(fLayer.initialExtent);

        })

        return fLayer
    }

    // var changeDetectionlayer0 = new ArcGISDynamicMapServiceLayer(changeDetectionlayerUrl, {
    //     "id": 'changeDetectionlayer0',
    //     "visible": true,
    //     "opacity": 0.6,
    //     // "visibleLayers":ids
    // });

    // changeDetectionlayer0.setVisibleLayers(ids);

    // var changeDetectionlayer1 = new ArcGISDynamicMapServiceLayer(changeDetectionlayerUrl, {
    //     "id": 'changeDetectionlayer1',
    //     "visible": true,
    //     "opacity": 0.6,

    //     // "visibleLayers":ids
    // });

    // changeDetectionlayer1.setVisibleLayers(ids);

    // $("#resultClose1").click(function () {
    //     $("#compareMapRow3").hide();
    //     // $(".compareMapRow").css("height", "100%");
    //     // $("#compareMapRow3").css("display", "flex");
    //     $(".compareMapRow").css("height", "100%");

    //     // $("#result").hide();
    //     // $("#map").css("height", "100%");
    //     // clickQueryGraphicsLayer.clear();

    // });

    function addGraphicsToMap(geometry, attributes) {
        var symbol = null;
        switch (geometry.type) {
            case "point":
                symbol = new SimpleMarkerSymbol(
                    SimpleMarkerSymbol.STYLE_SQUARE, 14,
                    new SimpleLineSymbol(
                        SimpleLineSymbol.STYLE_SOLID,
                        new Color([0, 255, 255]), 2),
                    new Color([0, 255, 0, 0]));
                break;
            case "polyline":
                symbol = new SimpleLineSymbol(
                    SimpleLineSymbol.STYLE_SOLID, new Color([
                        0, 255, 255, 1
                    ]), 4);
                break;
            case "polygon":
                symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
                    new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                        new Color([0, 255, 255]), 2), new Color([50, 50, 50, 0.1])
                );
                break;
        }
        var _graphic1 = new Graphic(geometry, symbol, attributes);
        var _graphic2 = new Graphic(geometry, symbol, attributes);
        clickQueryGraphicsLayer1.add(_graphic1);
        clickQueryGraphicsLayer2.add(_graphic2);
        maps[0].removeLayer(clickQueryGraphicsLayer1);
        maps[0].addLayer(clickQueryGraphicsLayer1, -1);
        maps[1].removeLayer(clickQueryGraphicsLayer2);
        maps[1].addLayer(clickQueryGraphicsLayer2, -1);

    }

    let createFeatureTable1 = (tableLayer) => {
        $("#tableSearchSelect").empty();
        $("#tableSearchInput").val("");

        let initFeatureTable = () => {
            const myTableNode = document.createElement("div");
            myTableNode.id = "myTableNode1";
            $("#result1").append(myTableNode);

            myFeatureTable1 = new FeatureTable({
                featureLayer: tableLayer,
                map: maps[0],
                batchCount: 1000,
                showAttachments: true,
                // only allows selection from the table to the map
                syncSelection: true,
                zoomToSelection: true,
                gridOptions: {
                    allowSelectAll: true,
                    allowTextSelection: true,
                    // sort: {
                    //     field: "st_area(shape)", descending: true
                    // }
                },
                editable: false,
                dateOptions: {
                    // set date options at the feature table level
                    // all date fields will adhere this
                    datePattern: "MMMM d, y"
                },
                // define order of available fields. If the fields are not listed in 'outFields'
                // then they will not be available when the table starts.
                fieldInfos: [{
                        name: 'st_area(shape)',
                        alias: '变化区域面积（平方米）',
                        editable: false //disable editing on this field
                    },
                    {
                        name: 'st_length(shape)',
                        alias: '变化区域周长（米）',
                        format: {
                            template: "${value}" //add mph at the of the value
                        }
                    },
                    {
                        name: 'type',
                        alias: 'Vehicle Type'
                    },
                    {
                        name: 'unitname',
                        alias: 'Unit Name'
                    }
                ],
                // menuFunctions: [
                //     //Add new Export to CSV menu function 
                //     {
                //         label: "Export to CSV",
                //         callback: customExportCSV
                //     }
                // ]
            }, 'myTableNode1');
            myFeatureTable1.startup();

            myFeatureTable1.on("load", () => {
                const fields = myFeatureTable1.columns;

                // fields.map((item) => {
                //     const field = item.field;
                //     const label = item.label;
                //     const fieldType = item.type;
                //     const option = "<option fieldType=" + fieldType + " value=" + field + ">" + label + "</option>";
                //     $("#tableSearchSelect1").append(option);
                // });
            })


            myFeatureTable1.on("row-select", function (evt) {


                activeMap = maps[0];
                clearActiveMapEvents();
                bindActiveMapEvents();

                console.log("row-select", evt);
                let selectedRows = evt.rows;
                let keyField, keyValue;

                map.infoWindow.clearFeatures();
                map.infoWindow.hide();

                var columns = myFeatureTable1.columns;

                columns.forEach(item => {
                    if (item.type == "esriFieldTypeOID") {
                        keyField = item.field;
                    }
                })

                // for (var key in selectedRows[0].data) {
                //     if (key.toUpperCase() == "OBJECTID") {
                //         keyField = key;
                //         break;
                //     } else if (key.toUpperCase() == "FID") {
                //         keyField = key;
                //         break;
                //     }
                // }

                if (tableLayer.url != null) {

                    let queryStr = "";
                    selectedRows.forEach((item, index) => {
                        let data = item.data;
                        keyValue = data[keyField];
                        if (index == 0) {
                            queryStr += keyField + " = " + keyValue;
                        } else {
                            queryStr += " or " + keyField + " = " + keyValue;
                        }
                    })

                    var query = new Query();
                    query.where = queryStr;
                    tableLayer.selectFeatures(query, FeatureLayer.SELECTION_NEW, function (result) {
                        clickQueryGraphicsLayer1.clear();
                        clickQueryGraphicsLayer2.clear();
                        result.forEach((item) => {
                            addGraphicsToMap(item.geometry, item.attributes);

                            // map.infoWindow.hide();
                            // map.infoWindow.setContent(item.getContent());
                            // map.infoWindow.setTitle(item.getTitle());
                            // map.infoWindow.show(item.geometry);
                        })
                    });
                } else {
                    let graphics = tableLayer.graphics;
                    clickQueryGraphicsLayer1.clear();
                    clickQueryGraphicsLayer2.clear();

                    selectedRows.forEach((item, index) => {
                        let data = item.data;
                        keyValue = data[keyField];

                    })

                    graphics.forEach((item, index) => {
                        if (item.attributes[keyField] == keyValue) {

                            addGraphicsToMap(item.geometry, item.attributes);

                            // map.infoWindow.hide();
                            // map.infoWindow.setContent(item.getContent());
                            // map.infoWindow.setTitle(item.getTitle());
                            // map.infoWindow.show(item.geometry);
                        }

                    })
                }

            });
        }

        if (myFeatureTable1 === undefined) {
            initFeatureTable();

        } else {
            myFeatureTable1.destroy();

            initFeatureTable();
        }


        //防止输入中文还在打字时触发搜索
        var tableFalg = true;
        $("#tableSearchInput").off("compositionstart")
        $("#tableSearchInput").on("compositionstart", function () {
            tableFalg = false;
        })
        $("#tableSearchInput").off("compositionend")
        $("#tableSearchInput").on("compositionend", function () {
            tableFalg = true;
        })
        $("#tableSearchInput").on("input", function () {
            setTimeout(() => {
                if (tableFalg) {
                    let keywords = $(this).val();
                    let field = $("#tableSearchSelect").val();
                    let type = $("#tableSearchSelect").find("option:selected").attr("fieldtype");

                    let sql;
                    if (keywords == "") {
                        sql = "1=1";
                    } else {
                        if (type == "esriFieldTypeString") {
                            sql = field + " like '%" + keywords + "%'";
                        } else {
                            sql = field + " = " + keywords;
                        }
                    }
                    tableLayer.setDefinitionExpression(sql);
                    myFeatureTable1.refresh();

                    // window.clearInterval(myInterval);
                }
            }, 100);
        })

    }
});